package com.xinjian.controller;

import com.xinjian.base.config.Config;
import com.xinjian.base.enums.OperatorFriendRequestTypeEnum;
import com.xinjian.base.enums.SearchFriendsStatusEnum;
import com.xinjian.pojo.Users;
import com.xinjian.pojo.bo.UsersBO;
import com.xinjian.pojo.vo.FriendRequestVO;
import com.xinjian.pojo.vo.MyFriendsVO;
import com.xinjian.pojo.vo.UsersVO;
import com.xinjian.service.UserService;
import com.xinjian.base.utils.FastDFSClient;
import com.xinjian.base.utils.FileUtils;
import com.xinjian.base.utils.JSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * app用户
 *
 * @author yyb
 * @create 2018-12-03-20:31
 */
@RestController
@RequestMapping("u")
@Api(value = "UserController|App用户")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private Config config;
    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "传递Users对象DTO，json格式传递数据", produces = "application/json")
    public JSONResult register(@RequestBody Users user) throws Exception {
        //判断用户名密码不能为空
        if (StringUtils.isBlank(user.getUserName()) || StringUtils.isBlank(user.getPassWord())) {
            return JSONResult.errorMsg("用户名密码不能为空！");
        }
        //判断用户名是否存在，不存在就注册,存在提示错误
        Boolean userNameIsExist = userService.queryUserNameIsExist(user.getUserName());
        Users usersResult;
        if (userNameIsExist) {
            return JSONResult.errorMsg("用户名已存在！");
        } else {
            //注册
            usersResult = userService.save(user);
        }
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(usersResult, usersVO);
        return JSONResult.ok(usersVO);
    }

    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "传递Users对象DTO，json格式传递数据", produces = "application/json")
    public JSONResult login(@RequestBody Users user) throws Exception {
        //判断用户名密码不能为空
        if (StringUtils.isBlank(user.getUserName()) || StringUtils.isBlank(user.getPassWord())) {
            return JSONResult.errorMsg("用户名密码不能为空！");
        }
        //判断用户名是否存在，如果存在就登录，不存在提示错误
        Boolean userNameIsExist = userService.queryUserNameIsExist(user.getUserName());
        Users usersResult;
        if (userNameIsExist) {
            //登录
            usersResult = userService.queryUserForLogin(user.getUserName(), user.getPassWord());
            if (usersResult == null) {
                return JSONResult.errorMsg("用户名密码不正确！");
            }
        } else {
            return JSONResult.errorMsg("用户名不存在！");
        }
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(usersResult, usersVO);
        return JSONResult.ok(usersVO);
    }

    /**
     * 上传用户头像
     *
     * @param usersBO
     * @return
     */
    @PostMapping("/uploadFaceBase64")
    public JSONResult uploadFaceBase64(@RequestBody UsersBO usersBO) throws Exception {
        //获取前段传过来的base64字符串，然后转换为文件对象再上传
        String base64Data = usersBO.getFaceData();
        String userFacePath = config.getUploadLocalPath() + usersBO.getUserId() + config.getUploadPictureSuffix();
        FileUtils.base64ToFile(userFacePath, base64Data);
        //上传文件到fastDFS
        MultipartFile faceFile = FileUtils.fileToMultipart(userFacePath);
        String url = fastDFSClient.uploadBase64(faceFile);

        //分割url
        String[] arr = url.split("\\.");
        String thumpImgUrl = arr[0] + config.getUploadSmallPictur() + arr[1];

        //更新用户头像
        Users user =Users.builder()
                .id(usersBO.getUserId())
                .faceImage(thumpImgUrl)
                .faceImageBig(url)
                .build();
        user = this.userService.updateUsersInfo(user);
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(user, usersVO);
        return JSONResult.ok(usersVO);
    }

    /**
     * 更新昵称
     *
     * @param usersBO
     * @return
     */
    @PostMapping("/setNickName")
    @ApiOperation(value = "更新昵称", notes = "传递UsersBO对象DTO，json格式传递数据", produces = "application/json")
    public JSONResult setNickName(@RequestBody UsersBO usersBO) throws Exception {
        //更新昵称
        Users user = new Users();
        user.setId(usersBO.getUserId());
        user.setNickName(usersBO.getNickName());
        user = this.userService.updateUsersInfo(user);
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(user, usersVO);
        return JSONResult.ok(usersVO);
    }


    /**
     * 搜索好友接口，根据账号做匹配查询而不是模糊查询
     *
     * @param myUserId
     * @param friendUserName
     * @return
     */
    @PostMapping("/search")
    @ApiOperation(value = "搜索好友接口", notes = "传递UsersBO对象DTO，json格式传递数据", produces = "application/json")
    public JSONResult searchUser(String myUserId, String friendUserName)
            throws Exception {
        //判断myUserId、friendUserName不能为空
        if (StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUserName)) {
            return JSONResult.errorMsg("");
        }
        //前置条件 -1.搜索的用户不存在，返回【无此用户】
        //前置条件 -2.搜索的账号是自己，返回【不能添加自己】
        //前置条件 -3.搜索的用户已经是你的好友，返回【该用户已经是你的好友】
        Integer status = userService.preconditionSearchFriends(myUserId, friendUserName);
        if (status == SearchFriendsStatusEnum.SUCCESS.status) {
            Users user = this.userService.queryUserInfonByUserName(friendUserName);
            UsersVO usersVO = new UsersVO();
            BeanUtils.copyProperties(user, usersVO);
            return JSONResult.ok(usersVO);
        } else {
            String errorMsg = SearchFriendsStatusEnum.getMsgByKey(status);
            return JSONResult.errorMsg(errorMsg);
        }
    }

    /**
     * 添加好友接口
     *
     * @param myUserId
     * @param friendUserName
     * @return
     */
    @PostMapping("/addFriendRequest")
    @ApiOperation(value = "添加好友接口", notes = "传递UsersBO对象DTO，json格式传递数据", produces = "application/json")
    public JSONResult addFriendRequest(String myUserId, String friendUserName) throws Exception {
        //判断myUserId、friendUserName不能为空
        if (StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUserName)) {
            return JSONResult.errorMsg("");
        }
        //前置条件 -1.搜索的用户不存在，返回【无此用户】
        //前置条件 -2.搜索的账号是自己，返回【不能添加自己】
        //前置条件 -3.搜索的用户已经是你的好友，返回【该用户已经是你的好友】
        Integer status = userService.preconditionSearchFriends(myUserId, friendUserName);
        if (status == SearchFriendsStatusEnum.SUCCESS.status) {
            userService.sendFriendRequest(myUserId, friendUserName);
            return JSONResult.ok();
        } else {
            String errorMsg = SearchFriendsStatusEnum.getMsgByKey(status);
            return JSONResult.errorMsg(errorMsg);
        }
    }

    /**
     * 查询我的好友列表
     *
     * @param userId
     * @return
     */
    @PostMapping("/myFriends")
    @ApiOperation(value = "查询好友列表", notes = "传递UsersBO对象DTO，json格式传递数据", produces = "application/json")
    public JSONResult myFriends(String userId) {
        //0.判断userId不能为空
        if (StringUtils.isBlank(userId)) {
            return JSONResult.errorMsg("");
        }
        //1.数据查询好友列表
        List<MyFriendsVO> myFriendsVO = this.userService.queryMyFriends(userId);
        return JSONResult.ok(myFriendsVO);
    }

    /**
     * 查询好友请求
     *
     * @param userId
     * @return
     */
    @PostMapping("/queryFriendRequests")
    @ApiOperation(value = "查询好友请求", notes = "传递UsersBO对象DTO，json格式传递数据", produces = "application/json")
    public JSONResult queryFriendRequests(String userId) {
        //0.判断userId不能为空
        if (StringUtils.isBlank(userId)) {
            return JSONResult.errorMsg("");
        }
        //1.数据查询好友列表
        List<FriendRequestVO> friendRequests = this.userService.queryFriendRequestList(userId);
        return JSONResult.ok(friendRequests);
    }

    /**
     * 接收方 通过或者忽略用户请求
     *
     * @param acceptUserId
     * @param sendUserId
     * @param operType
     * @return
     */
    @PostMapping("/operFriendRequest")
    @ApiOperation(value = "接收方,通过或者忽略用户请求", notes = "传递UsersBO对象DTO，json格式传递数据", produces = "application/json")
    public JSONResult operFriendRequest(String acceptUserId, String sendUserId, Integer operType) {
        //0.判断acceptUserId、sendUserId、operType不能为空
        if (StringUtils.isBlank(acceptUserId) || StringUtils.isBlank(sendUserId) || operType == null) {
            return JSONResult.errorMsg("");
        }
        //1.如果operType没有对应枚举值，则直接抛出空错误信息
        if (StringUtils.isBlank(OperatorFriendRequestTypeEnum.getMsgByType(operType))) {
            return JSONResult.errorMsg("");
        }
        if (operType == OperatorFriendRequestTypeEnum.IGNORE.type) {
            // 2. 判断如果忽略好友请求，则直接删除好友请求的数据库表记录
            userService.deleteFriendRequest(sendUserId, acceptUserId);
        } else if (operType == OperatorFriendRequestTypeEnum.PASS.type) {
            // 3. 判断如果是通过好友请求，则互相增加好友记录到数据库对应的表
            //	   然后删除好友请求的数据库表记录
            userService.passFriendRequest(sendUserId, acceptUserId);
        }
        // 4. 数据库查询好友列表
        List<MyFriendsVO> myFirends = userService.queryMyFriends(acceptUserId);
        return JSONResult.ok(myFirends);
    }

    /**
     * 用户手机端获取未签收的消息列表
     *
     * @param acceptUserId
     * @return
     */
    @PostMapping("/getUnReadMsgList")
    public JSONResult getUnReadMsgList(String acceptUserId) {
        //0.判断acceptUserId、sendUserId、operType不能为空
        if (StringUtils.isBlank(acceptUserId)) {
            return JSONResult.errorMsg("");
        }

        // 4. 查询列表
        List<com.xinjian.pojo.ChatMsg> nnReadList = userService.getUnReadMsgList(acceptUserId);
        return JSONResult.ok(nnReadList);
    }

}
